package com.erbao.interview;

import java.util.LinkedList;

/**
 * 固定容量的同步容器，拥有方法put和get，以及getCount
 * 2个生产者 10个消费者
 * @author CaoBaoYin
 * @since 2022/2/27 21:13
 */
public class ConsumerProducer {

    public static void main(String[] args) {
        final FixedCapacity<String> fixedCapacity = new FixedCapacity<>(10);

        Runnable consumer = () ->{
            for (int i = 0; i < 5; i++) {
                System.out.println(Thread.currentThread().getName()+" get "+ fixedCapacity.get());
            }
        };

        Runnable producer = () -> {
            for (int i = 0; i < 25; i++) {
                fixedCapacity.put(Thread.currentThread().getName() + "_" + i);
            }
        };

        for (int i = 0; i < 2; i++) {
            new Thread(producer, "p"+i).start();
        }

        for (int i = 0; i < 10; i++) {
            new Thread(consumer, "c"+i).start();
        }
    }


}


class FixedCapacity<E> {
    private LinkedList<E> list;
    private int limit;

    public FixedCapacity(int limit) {
        this.limit = limit;
        list = new LinkedList<>();
    }

    public synchronized void put (E e) {
        while (list.size() == this.limit) {
            System.out.println("capacity is full");
            try {
                wait();
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
        list.add(e);
        notifyAll();
    }

    public synchronized E get () {
        while (list.size() == 0) {
            System.out.println("capacity is empty");
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        E e = list.removeFirst();
        notifyAll();
        return e;
    }

    public int getCount () {
        return list.size();
    }
}
